﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;

public class GameObjectDeath : MonoBehaviour 
{
    /// <summary>
    /// If dies on collision, then you can exclude items based on their tags
    /// </summary>
    public string[] CollisionDeathExceptionTags;

    public bool DieOnCollision = false;
    public bool DieAfterTime = false;

    /// <summary>
    /// Life span of object in seconds if it dies after a given time span.
    /// </summary>
    public float LifeSpan = 3;

    /// <summary>
    /// Hide the object when it dies for this number of seconds before  it is
    /// totaly destroyed, maybe the obect has a particle trail you want to
    /// keep alive before you kill the object :)
    /// </summary>
    public float HideOnDeath = 0;

    TimeSpan StartTime;
    TimeSpan Duration;
    bool TimeUp { get { return TimeLeft < TimeSpan.Zero; } }
    TimeSpan TimeLeft { get { return (Duration - (DateTime.Now.TimeOfDay - StartTime)); } }

    List<string> deathCheckList;

    void Awake()
    {
        deathCheckList = new List<string>(CollisionDeathExceptionTags);
    }

	// Use this for initialization
	void Start () 
    {
        if (DieAfterTime)
        {
            StartTime = DateTime.Now.TimeOfDay;
            Duration = new TimeSpan(0, 0, 0, 0, (int)(LifeSpan * 1000));
        }
	}
	
	// Update is called once per frame
	void Update () 
    {
        if (DieAfterTime && TimeUp)
            Die();
	}

    void OnCollisionEnter(Collision collision)
    {
        if (DieOnCollision)
        {
            // If the object is not in the list of tag excluded tag items kill it
            if (!deathCheckList.Contains(collision.gameObject.tag))
            {
                if (DieAfterTime)
                    DieAfterTime = false;

                Die();
            }
        }
    }

    void Die()
    {
        if (HideOnDeath != 0)
        {
            gameObject.renderer.enabled = false;

            if (gameObject.rigidbody != null)
                gameObject.rigidbody.isKinematic = true;

            if (gameObject.collider != null)
                gameObject.collider.enabled = false;
        }

        Destroy(gameObject, HideOnDeath);
    }
}
